package utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class Mybatisutil {
    private static SqlSessionFactory factory;
    private  static final ThreadLocal<SqlSession> local = new ThreadLocal<SqlSession>();
    static {
        try {
            //加载了主配置文件
            InputStream is = Resources.getResourceAsStream("mybatis.config.xml");
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            factory = builder.build(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static SqlSessionFactory getFactory() {
        return factory;
    }

    //手动事务管理
    public static SqlSession getSqlSession() {
        return  getSqlSession(false);//这个加进来以后，外面调用getSession就是手动提交，而调用Mybatisutil.getMapper()则是自动提交
    }
    private static SqlSession getSqlSession(boolean AutoCommit) {//true自动事务管理，false 手动事务管理
        SqlSession sqlSession = local.get();
        if(sqlSession == null){
            sqlSession=factory.openSession();//自动提交
            local.set(sqlSession);
        }
        return sqlSession;
    }


    //自动事务管理，自动提交
    public  static <T extends Object>T getMapper(Class<T> c){
        SqlSession sqlSession = getSqlSession(true);
        return sqlSession.getMapper(c);
    }
}
